<template>
  <el-card v-show="show" shadow="never" class="aui-card--fill">
    <!-- <h4 style="text-align: left">{{ house.name }}</h4> -->
    <!-- <img :src="getResourceURL()" class="image"> -->
    <div class="mod-sys__dict">
      <!-- <el-row :gutter="50" v-for="row in grids" type="flex" :key="row" class="el-row">
        <el-col v-for="col in row" :key="col.id" :span="24 / house.columns" class="el-col"><div class="grid-content bg-purple">{{col.earmark ? col.earmark : '空'}}</div></el-col>
      </el-row> -->
      <!-- <span>{{JSON.stringify(grids)}}</span> -->
      <el-table :data="grids" fit stripe style="width= 100%;" show-ovflow-tooltip @cell-click="gridSelect" :cell-class-name="cellClassName" :cell-style="setCellStyle">
        <el-table-column align="center" :label="house.name" :width="100" style="height: 350px" fixed>
          <template slot-scope="scope">
            <el-badge class="item">
              <el-button size="mini">
                {{house && house.rowStart ? String.fromCharCode(scope.$index + (house.rowStart ? house.rowStart.charCodeAt() : 1)) : scope.$index + 1}}
              </el-button>
            </el-badge>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in column" :key="item" align="center" :label="'' + item" height="1000px" style="height: 700px; overflow: unset">
          <template slot-scope="scope">
            <template v-if="!scope.row[index].mounts">
              <el-badge v-show="!state || breed.state==state" :value="breed.parity" v-for="breed in scope.row[index]" :style="[{border: ((pig && breed.id==pig.id) ? '1px solid blue' : '1px solid white')}, {color: ((pig && breed.id==pig.id) ? 'red' : 'black')}]" :key="breed.id" class="item">
                <el-button size="mini" @click="breedClick(breed)" :class="'state-' + breed.state">
                  <i v-if="breed.gender == 1" class="el-icon-male"></i>
                  <i v-if="breed.gender == 0" class="el-icon-female"></i>
                  {{breed.earmark}}
                </el-button>
              </el-badge>
            </template>
            <el-badge :value="scope.row[index].dayAge" class="item" :style="[{border: ((current.row==scope.$index && current.column==index) ? '1px solid blue' : '1px solid white')}]" v-if="scope.row[index].mounts">
              <el-button size="mini" @click="gridClick(scope.$index, index)">
                {{scope.row[index].mounts}}
              </el-button>
            </el-badge>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>
</template>
<style scoped>
  .image {
    width: 60%;
    display: block;
    margin: 0 auto 30px auto;
  }

  .el-table {
    overflow: unset;
  }

  .el-table /deep/ td {
    white-space: nowrap;
    width: fit-content;
  }

  .el-table /deep/ .cell {
    white-space: nowrap;
    overflow: visible!important;
    width: fit-content;
    line-height: 100%;
    display: inline-grid;
  }
  .el-table__body-wrapper {
    overflow: unset;
  }

  ::v-deep .el-table__fixed-right {
    height: 100% !important;
  }

  .el-row {
    margin-bottom: 20px;
    height: 100px;
    display: flex;
    flex-wrap: wrap;
    overflow: unset;
  }

  .el-col {
    background-color: bisque;
    overflow: unset;
  }

  .grid-cell {
    overflow: unset!important;;
  }

</style>

<script>
export default {
  name: 'Grid',
  data () {
    return {
      grids: [],
      house: {},
      show: false,
      column: [],
      current: {}
    }
  },
  props: {
    value: [Object],
    house_id: String,
    grid: [Object],
    pig: [Object],
    placeholder: String,
    state: [Number],
    alone: [String],
    type: [String]
  },
  watch: {
    'grid': {
      handler () {
        this.init()
      },
      immediate: true,
      deep: true
    },
    'pig': {
      handler (newVal, oldVal) {
        this.updatePig(newVal, oldVal)
      },
      immediate: true,
      deep: true
    },
    'house_id': {
      handler () {
        if (this.house_id) {
          this.getHouse()
        }
      },
      immediate: true
    },
    'state': {
      handler () {
        this.updateShow()
      },
      immediate: true
    }
  },
  methods: {
    isNumber (value) {
      var reg = /^\+?[1-9][0-9]*$/
      return reg.test(value)
    },
    updateShow () {
      let that = this
      this.show = false
      for (var r = 0; r < that.house.rows; ++r) {
        for (var c = 0; c < that.house.columns; ++c) {
          let pigs = that.grids[r][c]
          let hasPig = false
          pigs.forEach(function (pig) {
            hasPig = true
            if (that.state === pig.state) {
              that.show = true
            }
          })
          if (!this.state && hasPig) {
            this.show = true
            break
          }
        }
      }
    },
    updatePig (r, t) {
      console.table(r, t)
      // this.$set(this.grids[t.grid.row], t.grid.column - 1, t)
    },
    cellClassName ({ row, column, rowIndex, columnIndex }) {
      row && (row.index = rowIndex)
      column && (column.index = columnIndex)
      return 'grid-cell'
    },
    setCellStyle ({ row, column, rowIndex, columnIndex }) {
      if (this.pig) {
        if (this.pig.grid && this.pig.grid.row - 1 === rowIndex && this.pig.grid.column === columnIndex) {
          return { 'background-color': '#009221', 'border': '1px solid red', 'overflow': 'unset' }
        } else if (this.pig.toGrid && this.pig.toGrid.row - 1 === rowIndex && this.pig.toGrid.column === columnIndex) {
          return { 'background-color': '#009221', 'overflow': 'unset' }
        }
      } else {
        return { 'overflow': 'unset' }
      }
    },
    gridClick (row, column) {
      this.$emit('gridClick', {})
    },
    gridSelect (row, col) {
      this.current = {}
      this.current.row = row.index
      this.current.column = col.index - 1
      this.current.name = this.getName(this.current.row, this.current.column)
      this.current.row += 1
      this.current.column += 1
      this.$emit('gridSelect', this.current)
    },
    breedClick (pig) {
      this.$emit('breedSelect', pig)
    },
    getName (row, col) {
      let rowStart, colStart
      if (this.grid) {
        rowStart = this.grid.rowStart
        colStart = this.grid.colStart
      } else {
        rowStart = this.house.rowStart
        colStart = this.house.colStart
      }
      let name = row + 1 + '-' + (col + 1)
      let spilt = '-'
      if (rowStart || colStart) {
        if (this.isNumber(rowStart)) {
          name = row + Number(rowStart)
        } else if ((rowStart.charCodeAt() >= 65 && rowStart.charCodeAt() < 84) || (rowStart.charCodeAt() >= 97 && rowStart.charCodeAt() < 116)) {
          name = String.fromCharCode(row + rowStart.charCodeAt())
          spilt = ''
        } else {
          name = row + 1
        }
        if (this.isNumber(colStart)) {
          name = name + spilt + (col + Number(colStart))
        } else if ((colStart.charCodeAt() >= 65 && colStart.charCodeAt() < 84) || (colStart.charCodeAt() >= 97 && colStart.charCodeAt() < 116)) {
          name = name + String.fromCharCode(col + colStart.charCodeAt())
        } else {
          name = name + spilt + (col + 1)
        }
      }
      return name
    },
    gridMerge ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex % 2 === 0) {
        if (columnIndex === 4) {
          return [1, 2]
        } else if (columnIndex === 5) {
          return [2, 3]
        }
      }
    },
    init () {
      if (this.house_id) {
        return
      }
      if (!this.grid || !this.grid.rows || !this.grid.columns) {
        this.show = false
        return
      }
      this.show = true
      let that = this
      // this.house.name = this.grid.name
      this.house = this.grid
      that.column = []
      that.grids = []
      if (that.grid.rows && that.grid.columns) {
        for (var i = 0; i < that.grid.columns; ++i) {
          if (this.isNumber(this.grid.colStart)) {
            that.column.push(i + Number(this.grid.colStart))
          } else if ((this.grid.colStart.charCodeAt() >= 65 && this.grid.colStart.charCodeAt() < 84) || (this.grid.colStart.charCodeAt() >= 97 && this.grid.colStart.charCodeAt() < 116)) {
            let r = String.fromCharCode(i + this.grid.colStart.charCodeAt())
            that.column.push(r)
          } else {
            that.column.push(i + 1)
          }
        }
        for (var r = 0; r < that.grid.rows; ++r) {
          that.grids.push([])
          // that.grids[r].push({ earmark: r + 1 })// 最后一列展示行号
          for (var c = 0; c < that.grid.columns; ++c) {
            // that.grids[r].push([])
            let name = r + 1 + '-' + (c + 1)
            let spilt = '-'
            if (this.grid.rowStart || this.grid.colStart) {
              if (this.isNumber(this.grid.rowStart)) {
                name = r + Number(this.grid.rowStart)
              } else if ((this.grid.rowStart.charCodeAt() >= 65 && this.grid.rowStart.charCodeAt() < 84) || (this.grid.rowStart.charCodeAt() >= 97 && this.grid.rowStart.charCodeAt() < 116)) {
                name = String.fromCharCode(r + this.grid.rowStart.charCodeAt())
                spilt = ''
              } else {
                name = r + 1
              }
              if (this.isNumber(this.grid.colStart)) {
                name = name + spilt + (c + Number(this.grid.colStart))
              } else if ((this.grid.colStart.charCodeAt() >= 65 && this.grid.colStart.charCodeAt() < 84) || (this.grid.colStart.charCodeAt() >= 97 && this.grid.colStart.charCodeAt() < 116)) {
                name = name + String.fromCharCode(c + this.grid.colStart.charCodeAt())
              } else {
                name = name + spilt + (c + 1)
              }
            }
            that.grids[r][c] = {
              mounts: name
            }
          }
        }
        console.table(that.grids)
      }
      that.$forceUpdate()
    },
    getState (state) {
      return 'danger'
    },
    getHouse () {
      var url = `/basic/house/${this.house_id}`
      let that = this
      return this.$http.get(url).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        that.column = []
        that.grids = []
        that.house = res.data
        //  生成grids
        if (that.house.rows && that.house.columns) {
          for (var i = 0; i < that.house.columns; ++i) {
            that.column.push(i + 1)
          }
          for (var r = 0; r < that.house.rows; ++r) {
            that.grids.push([])
            // that.grids[r].push({ earmark: r + 1 })// 最后一列展示行号
            for (var c = 0; c < that.house.columns; ++c) {
              that.grids[r].push([])
            }
          }
          console.table(that.grids)
        }
        if (that.type === '1') {
          this.getGrowth()
        } else {
          this.getBreed()
        }
        this.$forceUpdate()
      }).catch(() => {})
    },
    getBreed () {
      var url = '/stock/pig/page?page=1&limit=500'
      if (this.house != null) {
        url += '&houseId=' + this.house_id
      }
      let that = this
      return this.$http.get(url).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let hasPig = false
        res.data.list.forEach(function (pig) {
          hasPig = true
          let items = pig['grid'].split('-')
          if (items.length === 2) {
            let pigs = that.grids[items[0] - 1][items[1] - 1]
            if (pig.state === 6 || pig.state === 7 || pig.state === 9) {
              pig.state = 3
            }
            pigs.push(pig)
            that.$set(that.grids[items[0] - 1], items[1] - 1, pigs)
            // that.grids[items[0]][items[1]] = pig
          }
          console.table(that.grids)
          // if (that.state && pig.state === that.state) {
          //   that.show = true
          // } else {
          //   that.show = true
          // }
        })
        that.$forceUpdate()
        that.show = hasPig
        if (that.alone) {
          that.show = (that.alone === '1')
        }
      }).catch(() => {})
    },
    getGrowth () {
      var url = '/stock/piggrowth/page?page=1&limit=500'
      if (this.house != null) {
        url += '&houseId=' + this.house_id
      }
      let that = this
      this.show = (this.alone === '1')
      return this.$http.get(url).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        res.data.list.forEach(function (pig) {
          let items = pig['grid'].split('-')
          if (items.length === 2) {
            that.$set(that.grids[items[0] - 1], items[1] - 1, pig)
            // that.grids[items[0]][items[1]] = pig
          }
          console.table(that.grids)
          that.$forceUpdate()
          that.show = true
        })
      }).catch(() => {})
    }
  }
}
</script>
